package com.ulife.order.components.util;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ObjectMapperFactory {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
        testModule.addDeserializer(Date.class, new DateJsonDeserializer());
        objectMapper.registerModule(testModule);
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
}

class DateJsonDeserializer extends JsonDeserializer {

    private SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");

    private SimpleDateFormat dt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        JsonToken t = jp.getCurrentToken();
        if (t == JsonToken.VALUE_NUMBER_INT) {
            return new Date(jp.getLongValue());
        }
        if (t == JsonToken.VALUE_NULL) {
            return (Date) getNullValue();
        }
        if (t == JsonToken.VALUE_STRING) {
            try {
                String str = jp.getText().trim();
                if (str.length() == 0) {
                    return (Date) getEmptyValue();
                }
                Date date = null;
                try {
                    date = dt2.parse(str);
                } catch (ParseException e) {
                    try {
                        date = dt1.parse(str);
                    } catch (ParseException e1) {
                        e1.printStackTrace();
                    }
                }
                return date;
            } catch (IllegalArgumentException iae) {
                return null;
            }
        }
        return null;
    }
}